/**
 * Created by x on 17-7-25.
 */
angular.module('tribalc').controller('amendApartmentController',
    ['$scope', '$rootScope','$state','$stateParams', 'Enum', 'Api', 'ApartmentInfoModel','Alert',
        function ($scope, $rootScope,$state, $stateParams,Enum, Api, ApartmentInfoModel,Alert){

            init();
            $scope.submitAmendApartinfo =submitAmendApartinfo;

            $scope.apartmentId = $stateParams.apartmentId;
            $scope.setupProvince = setupProvince;
            $scope.setupCity = setupCity;
            $scope.setupDistrict = setupDistrict;
            $scope.uploadFixedApartmentPictures = uploadFixedApartmentPictures;
            getCitys();

            getCommunityList();
            function getCommunityList() {
                Api.getCommunityList(function (result) {
                    $scope.communityList = result.data;
                })
            }

            //保存按钮
            function submitAmendApartinfo(apartinfomation) {
                if ($scope.subwayLine && $scope.subwayStation)
                    apartinfomation.subway = $scope.subwayLine + "/" + $scope.subwayStation;
                apartinfomation.pictures = $scope.upload.pictures;
                if ($scope.buildFloor.indexOf('/') >= 0 && $scope.buildFloor.split('/').length == 2) {
                    apartinfomation.floor = parseInt($scope.buildFloor.split("/")[0]);
                    apartinfomation.buildingHeight = parseInt(($scope.buildFloor.split("/")[1].split("层"))[0]);
                } else {
                    return Alert.alertBox('请检查楼层格式')
                }
                var facilitiesListinfo = getfaciliyiesInfo();
                getFacilities(facilitiesListinfo);
                apartinfomation.facilities = facilitiesListinfo.facilities;

                var tagsListinfo = gettagsInfo();
                getTags(tagsListinfo);
                apartinfomation.tags = tagsListinfo.tags;

                var apartmentInfo = new ApartmentInfoModel(apartinfomation);

                if (!checkInformation(apartmentInfo)) {

                    Alert.alertBox("请把信息填写完整");
                }
                else {
                    if (checkTypeOfInformation(apartmentInfo))
                    {
                        Api.perfectApartmentInfo(apartmentInfo,function (result) {
                            Alert.alertBox('房源修改成功！',function () {
                                $state.go('company.companyApartmentManage');
                            });
                        });
                    }
                }
            }

            function getfaciliyiesInfo() {
                var info={
                    facilities:[]
                };
                return info;
            }

            function gettagsInfo() {
                var info={
                    tags:[]
                };
                return info;
            }


            function checkTypeOfInformation(apartmentInfo)
            {
                var status = true;
                var require_keys = ['address', 'area', 'around', 'cityId',
                    'communityId', 'disId', 'floor', 'name', 'price', 'provinceId', 'subway',
                    'subwayDistance', 'traffic', 'type','buildingName','buildingId'];
                // var unrequire_keys = ["buildingHeight","facilities","pictures","tags"];//['number','object','object','object']
                var require_types = ['string','number','string','string','string','string','number','string','number',
                    'string','string','string','string','string','string','string'];
                var data = {address:"房源地址", area:'房源面积', around:'房源周边', buildingHeight:'房源楼层',
                    cityId:'房源所在地', communityId:'社区', disId:'房源所在地', facilities:'房源配置', floor:'房源楼层',
                    name:'房源名称', pictures:'房源图片', price:'房源价格', provinceId:'房源所在地', subway:'周边地铁',
                    subwayDistance:'交通距离', tags:'房源标签', traffic:'房源交通', type:'房源户型',
                    buildingName:'楼栋名称',buildingId:'楼栋编号'};
                for (var i = 0; i < require_keys.length; i++)
                {
                    if (typeof (apartmentInfo[require_keys[i]]) != require_types[i] || require_types[i] == 'number'? isNaN(apartmentInfo[require_keys[i]]) : false)
                    {
                        Alert.alertBox(data[require_keys[i]]+"格式不正确");
                        status = false;
                        break
                    }
                }
                return status;
            }
            function checkInformation(apartmentInfo) {
                var status = true;
                var keys = ['name','price','area','communityId','address','subway','subwayDistance','type',
                    'floor','around','traffic', 'disId','provinceId','cityId','buildingName','buildingId'];
                for (var i = 0; i < keys.length; i++) {
                    if(apartmentInfo[keys[i]] == null){
                        // console.log(keys[i]);
                        status = false;
                        break
                    }
                }
                return status
            }

            //获取房源信息
            getApartmentDetail();
            function getApartmentDetail() {
                Api.getCompanyDetail(null,function(result) {
                    Api.getApartmentListInfo(result.data.communityId,$scope.apartmentId,function (result) {
                        var apartment = new ApartmentInfoModel(result.data);
                        var community = _.find($scope.communityList,function (commun) {
                            return commun.id == apartment.communityId;
                        });
                        apartment.community = {id:community.id,name:community.name};
                        $scope.subwayLine = apartment.subway.split('/')[0];
                        $scope.subwayStation = apartment.subway.split('/')[1];
                        $scope.buildFloor = apartment.floor+"/"+apartment.buildingHeight+"层";
                        $rootScope.RootapartmentInfo = apartment;
                        $scope.current_province = _.find($scope.citys.province,function (province) {
                            return province.provinceId == apartment.provinceId
                        })
                        $scope.citysModel = $scope.current_province.city;
                        $scope.current_city = _.find($scope.current_province.city,function (city) {
                            return city.cityId == apartment.cityId
                        })
                        $scope.districtModel = $scope.current_city.district;
                        $scope.current_district = _.find($scope.current_city.district,function (district) {
                            return district.districtId == apartment.disId
                        })
                        bindClickEventToFacilitiesTag(apartment.facilities);
                        bindClickEventToTag(apartment.tags);
                        setupApartmentInfoModel();

                    });

                });
            }



            function bindClickEventToFacilitiesTag(facilities) {
                $rootScope.facilitiesinfo = facilities||[];
                $('#facilities>div>div').click(function () {
                    if ($(this).hasClass('active'))
                    {
                        facilities.splice(facilities.indexOf($(this).text()),1);
                        $rootScope.facilitiesinfo=facilities;
                        $(this).removeClass('active');
                    }
                    else
                    {
                        facilities.push($(this).text());
                        $rootScope.facilitiesinfo=facilities;
                        $(this).addClass('active');
                    }
                });
            }
            function getFacilities(apartfacilities) {
                // console.log(apartfacilities)
                apartfacilities.facilities =$rootScope.facilitiesinfo;

                return apartfacilities;
            }



            function bindClickEventToTag(tags) {
                $rootScope.tagsInfo = tags;
                $('#tagsInfo>div>span').click(function () {
                    if ($(this).hasClass('active'))
                    {
                        tags.splice(tags.indexOf($(this).text()),1);
                        $rootScope.tagsInfo=tags;
                        $(this).removeClass('active');
                    }
                    else
                    {
                        tags.push($(this).text());
                        $rootScope.tagsInfo=tags;
                        $(this).addClass('active');
                    }
                });
            }
            function getTags(apartfacilities) {
                apartfacilities.tags =$rootScope.tagsInfo;
                return apartfacilities;
            }



            function setupApartmentInfoModel() {
                $rootScope.$watch('RootapartmentInfo',function (newapartInfo) {
                    if (newapartInfo) {
                        $rootScope.apartmentInfoModel = new ApartmentInfoModel(newapartInfo);
                        $scope.apartmentInfoModel.community = {id:newapartInfo.community.id,name:newapartInfo.community.name};
                        getUploadImage($scope.apartmentInfoModel.pictures);
                    }
                });
            }

            function getUploadImage(pictures){
                $scope.upload = {
                    pictures: pictures ? pictures: []
                };
                // console.log($scope.upload);
            }




            function setupProvince(province) {
                $scope.citysModel = province.city;
                $scope.apartmentInfoModel.provinceId = province.provinceId;
            }

            function setupCity(city) {
                $scope.apartmentInfoModel.cityId = city.cityId;
                $scope.districtModel = city.district;
            }

            function setupDistrict(district) {
                $scope.apartmentInfoModel.disId = district.districtId;
            }

            function getCitys() {
                Api.getChinaCitysJson(function (result) {
                    $scope.citys=result;
                });
            }
            function init() {
                $scope.uploadApartmentPictures =uploadApartmentPictures

            }

            $scope.to_right_image_container = function () {
                $('#imageContainer').addClass('pro-write-picture-right')
            };
            $scope.to_left_image_container=to_left_image_container;
            function to_left_image_container() {
                $('#imageContainer').removeClass('pro-write-picture-right')
            }

            function getComunityIdUrl() {
                return 'communitys/'+ $rootScope.RootCompanyInfo.communityId;
            }
            function uploadApartmentPictures(ele) {
                var $divEle = $(ele).parent();
                var file = ele.files[0];
                var comunityIdUrl=getComunityIdUrl()
                var index = $(".pro-write-picture-content .pro-write-pictures").index($($divEle).parent());
                console.log(index)
                setupPictures($($divEle), file);
                // uploadNumber++;
                uploadPicture(file,comunityIdUrl,function (imgeUrl) {
                    $scope.$apply(function () {
                        console.log(imgeUrl);
                        $scope.upload.pictures[index] = imgeUrl;
                    });
                });
            }
            function uploadFixedApartmentPictures(ele) {
                var $divEle = $(ele).parent();
                var file = ele.files[0];
                var comunityIdUrl=getComunityIdUrl()
                var index = $(".pro-write-picture-content .pro-write-pictures").index($($divEle).parent());
                setupPictures($($divEle), file);
                // uploadNumber++;
                uploadPicture(file,comunityIdUrl,function (imgeUrl) {
                    $scope.$apply(function () {
                        $scope.upload.pictures[index] = imgeUrl;
                    });
                });
            }
            var uploadNumber=0
            function uploadPicture(file,comunityIdUrl,sucFuc) {
                Api.uploadPicture(hex_md5(file),comunityIdUrl,function (result) {
                    console.log(result)
                    Api.callAliyunPicture(result.data.objectKey, result.data.url, file, function (result) {
                        console.log(result)
                        sucFuc(result);
                    }, function () {
                        uploadNumber--
                    });
                }, function () {
                    uploadNumber--
                });
            }

            function setupPictures($divEle, file) {
                var fileReader = new FileReader();
                fileReader.onload = function () {
                    var imgSrc = fileReader.result;
                    if (imgSrc) {
                        $divEle.find('img').attr("src", imgSrc);
                        $divEle.addClass("pro-logo-completed");

                    }
                };
                fileReader.readAsDataURL(file);
            }


            function formatPicturePath(apartpic) {

                var pictures=[];
                var aliyu="https://buluo-gs-pictures.oss-cn-beijing.aliyuncs.com/";
                if (apartpic.pictures){
                    for (var i=0;i<apartpic.pictures.length;i++){

                        if(apartpic.pictures[i].indexOf(aliyu) !== -1){
                            apartpic.pictures[i]="oss://" + apartpic.pictures[i].split(aliyu)[1];
                            console.log(apartpic.pictures[i])

                        }
                        pictures.push(apartpic.pictures[i]);
                    }

                    return apartpic.pictures=pictures;
                }
                return apartpic;
            }


        }]);